package com.aurora.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.aurora.common.utils.PageUtils;
import com.aurora.common.utils.Query;
import com.aurora.gulimall.product.service.CategoryBrandRelationService;
import com.aurora.gulimall.product.vo.Catelog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.aurora.gulimall.product.dao.CategoryDao;
import com.aurora.gulimall.product.entity.CategoryEntity;
import com.aurora.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**获取三级分类
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //2、组装成父子结构
        //2.1 找到所有的一级分类
        List<CategoryEntity> level1Menus = categoryEntities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(menus->{
                    //1、递归寻找子菜单
                    menus.setChildren(getChildren(menus,categoryEntities));
                    return menus;
                })
                .sorted((menus1,menus2)->{
                    //2、排序
                    return (menus1.getSort() == null?0:menus1.getSort()) - (menus2.getSort()==null?0:menus2.getSort());
                })
                .collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenusByIds(List<Long> asList) {
        //TODO 1、检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCateLogPath(Long attrGroupId) {
        List<Long> paths = new ArrayList<>();
        getParentIds(attrGroupId,paths);
        Collections.reverse(paths);
        return (Long[]) paths.toArray(new Long[paths.size()]);
    }

    /**
     * 级联更新
     * @CacheEvict 失效模式
     * 1、同时进行多种缓存操作
     * @param category
     */
    @Transactional
    @Override
//    @Caching(evict = {
//            @CacheEvict(value = "catagory",key = "'getLevel1Categorys'"),
//            @CacheEvict(value = "catagory",key = "'getCatalogJson'"),
//    })
    @CacheEvict(value = "catagory", allEntries = true)
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    /**
     * 首页-获得一级分类
     *
     * @return
     */
    @Override
    //缓存的数据需要指定放到哪个名字的缓存【缓存的分区（按照业务类型区分œ）】
//    @Cacheable(value = {"catagory"},key = "'level1Catagorys'")
    @Cacheable(value = {"catagory"},key = "#root.method.name")
    //1、代表当前方法的结果需要缓存。如果缓存中有，方法不调用；没有则调用方法，并将方法结果放入缓存
    //2、key默认自动生成： 缓存名字：：SimpleKey【】
    //3、缓存的value值。默认使用jdk序列化机制。将序列化后的数据存到redis
    //4、默认时间是-1
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1catagorys...");
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }


    /**缓存注解更新缓存分类信息
     * @return
     */
@Cacheable(value = "catagory",key = "#root.methodName")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //1、查出所有1级分类
        List<CategoryEntity> level1Categorys = getParentCid(selectList,0l);
        Map<String, List<Catelog2Vo>> parentId = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(),
                v -> {
                    //1、每一个一级分类，查到这个一级分类的二级分类
                    List<CategoryEntity> categoryEntities = getParentCid(selectList,v.getCatId());
                    //2、封装上面的结果
                    List<Catelog2Vo> catelog2Vos = null;
                    if (categoryEntities != null) {
                        catelog2Vos = categoryEntities.stream().map(l2 -> {
                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                            //1、找当前二级分类的三级分类封装成vo
                            List<CategoryEntity> level3Catelogs = getParentCid(selectList,l2.getCatId());
                            if(level3Catelogs != null){
                                List<Catelog2Vo.Catelog3Vo> collect = level3Catelogs.stream().map(l3 -> {
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                                catelog2Vo.setCatalog3List(collect);
                            }
                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return catelog2Vos;
                }));


        return parentId;
    }
    /**从缓存中获取数据
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJson2() {

        /**
         * 1、空结果缓存：解决缓存穿透
         * 2、设置过期时间（加随机值）：解决缓存雪崩问题
         * 3、加锁：解决缓存击穿问题
         *
         *
         *
         * */
        //1、从缓存中取数据
        String catagory = stringRedisTemplate.opsForValue().get("catagory");
        //加入缓存
        if(StringUtils.isEmpty(catagory)){
            log.error("缓存未命中，查询数据库。。。");
            //2、从数据库中查数据
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLock();

        }
        //将字符串转换成对象
        Map<String, List<Catelog2Vo>> stringListMap =
                JSON.parseObject(catagory, new TypeReference<Map<String, List<Catelog2Vo>>>() {
                });
        return stringListMap;
    }


    /**从数据库中获取数据
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithLocalLock() {
        /**只要是同一把锁，就能锁住需要这个锁的所有线程
         * 1、synchronized（this）或加到方法上：springboot所有的组件在容器中都是单例的
         *本地锁：synchronized，JUC（lock），在分布式情况下，想要锁住所有，必须使用分布式锁
         * */
        synchronized (this){
            return getDataFromDB();
        }
    }
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {
//        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", "111");
        String uuid = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid,30,TimeUnit.SECONDS);
        if(lock){//加锁成功
            //设置过期时间
//            stringRedisTemplate.expire("lock",30, TimeUnit.SECONDS);//必须和加锁是同一个操作
            Map<String, List<Catelog2Vo>> dataFromDB = null;
            try {
                dataFromDB = getDataFromDB();
            } finally {
                //删除锁
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                Long deleteLockStatus = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class)
                        , Arrays.asList("lock"), uuid);
            }
//            String needDeleteLock = stringRedisTemplate.opsForValue().get("lock");
//            if(uuid.equals(needDeleteLock)){
//                stringRedisTemplate.delete("lock");//删除锁
//            }
            return dataFromDB;
        }else{
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return getCatalogJsonFromDbWithRedisLock();//自旋
        }
    }

    /**
     * 缓存里面的数据如何和数据库保持一致
     * 缓存数据一致性
     * 1.双写模式
     * 2.失效模式
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        RLock lock = redissonClient.getLock("catalogJson-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> dataFromDB = null;
            try {
                dataFromDB = getDataFromDB();
            } finally {
               lock.unlock();
            }
            return dataFromDB;
    }


    private Map<String, List<Catelog2Vo>> getDataFromDB() {
        //得到锁后，应该再去缓存中确定一次，如果没有菜需要继续查询
        String catagory = stringRedisTemplate.opsForValue().get("catagory");
        if(!StringUtils.isEmpty(catagory)){
            Map<String, List<Catelog2Vo>> stringListMap =
                    JSON.parseObject(catagory, new TypeReference<Map<String, List<Catelog2Vo>>>() {
                    });
            return stringListMap;
        }
        log.error("查询数据库。。。");
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //1、查出所有1级分类
        List<CategoryEntity> level1Categorys = getParentCid(selectList,0l);
        Map<String, List<Catelog2Vo>> parentId = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(),
                v -> {
                    //1、每一个一级分类，查到这个一级分类的二级分类
                    List<CategoryEntity> categoryEntities = getParentCid(selectList,v.getCatId());
                    //2、封装上面的结果
                    List<Catelog2Vo> catelog2Vos = null;
                    if (categoryEntities != null) {
                        catelog2Vos = categoryEntities.stream().map(l2 -> {
                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                            //1、找当前二级分类的三级分类封装成vo
                            List<CategoryEntity> level3Catelogs = getParentCid(selectList,l2.getCatId());
                            if(level3Catelogs != null){
                                List<Catelog2Vo.Catelog3Vo> collect = level3Catelogs.stream().map(l3 -> {
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                                catelog2Vo.setCatalog3List(collect);
                            }
                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return catelog2Vos;
                }));

        //3、查数据库 并将数据放入缓存
        catagory = JSON.toJSONString(parentId);
        stringRedisTemplate.opsForValue().set("catagory",catagory);

        return parentId;
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList,Long parent_cid) {
//        return baseMapper.selectList(
//                new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        List<CategoryEntity> collect = selectList.stream().filter(item -> {
            return item.getParentCid() == parent_cid;
        }).collect(Collectors.toList());
        return collect;
    }

    private List<Long> getParentIds(Long attrGroupId, List<Long> paths){
        paths.add(attrGroupId);
        CategoryEntity category = this.getById(attrGroupId);
        if(category.getParentCid() != 0){
            getParentIds(category.getParentCid(), paths);
        }
        return paths;

    }

    //递归设置CategoryEntity下属子级
    private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> childrenList = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId())
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                    return categoryEntity;
                })
                .sorted((menus1, menus2) -> {
                    return (menus1.getSort() == null?0:menus1.getSort()) - (menus2.getSort()==null?0:menus2.getSort());
                })
                .collect(Collectors.toList());
        return childrenList;
    }

}